package com.chinaedu.oc.action.manageuser;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chinaedu.oc.context.Common.Session;
import com.chinaedu.oc.dao.managegroup.ManageGroupDao;
import com.chinaedu.oc.dao.manageuser.ManageUserDao;
import com.chinaedu.oc.dao.membership.MemberShipDao;
import com.chinaedu.oc.entity.manageuser.ManageUser;
import com.chinaedu.oc.entity.manageuser.ManageUserVO;
import com.chinaedu.oc.service.manageuser.ManageUserLoginService;
import com.chinaedu.oc.service.manageuser.ManageUserService;
import com.chinaedu.oc.util.common.IdCreater;
import com.chinaedu.oc.util.plugin.PageParams;
import com.chinaedu.oc.utils.ProcessResult;
import com.google.common.collect.Maps;

/**
 * @author lidan
 * 后台用户管理   
 * status  0:禁用   1：使用
 */
@Controller
@RequestMapping("/user")
public class ManageUserAction {
	@Resource
	private ManageUserDao manageUserDao;
	@Resource
	private ManageGroupDao manageGroupDao;
	@Resource
	private ManageUserLoginService manageUserLoginService;
	@Resource
	private MemberShipDao memberShipDao;
	@Resource
	private ManageUserService manageUserService;
	/**
	 * 获取后台用户列表(分页)
	 * @param request
	 * @param model
	 * @param pageNum   开始条数
	 * @param pageSize  每页条数
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public ProcessResult list(HttpServletRequest request,Model model,
							@RequestParam(value = "start", defaultValue = "0") int start,
							@RequestParam(value = "length", defaultValue = "10") int pageSize) {
		ProcessResult pr= new ProcessResult();
		//处理分页
		PageParams<ManageUserVO> params = new PageParams<ManageUserVO>();
		params.setPageParam(start, pageSize);
		params.setParam(new ManageUser("1"));
		List<ManageUserVO> users = manageUserDao.getUserList(params);
		users.forEach(u->{
			u.setDeptName("学校事业部");
		});
		pr.setRecordsFiltered(params.getPageQueryResult().getTotal());
		pr.setData(users);
		pr.setStatus(true);
		return pr;
	}
	
	/**
	 * 按条件查询
	 * @param request
	 * @param manageUser
	 * @param start
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/searchUser")
	@ResponseBody
	public ProcessResult searchUser(HttpServletRequest request,
									@ModelAttribute ManageUser manageUser,
									@RequestParam(value = "start", defaultValue = "0") int start,
									@RequestParam(value = "length", defaultValue = "10") int pageSize
									) {
		PageParams<ManageUser> params = new PageParams<ManageUser>();
		params.setPageParam(start, pageSize);
		params.setParam(new ManageUser("1"));//这加查询条件，放到对象中 对象set到params中
		List<ManageUserVO> users = manageUserDao.getUserList(params);
		ProcessResult pr= new ProcessResult();
		pr.setData(users);
		pr.setStatus(true);
		return pr;
	}
	
	/**
	 * 增加、更新后台用户【及用户关系表】
	 * @param request
	 * @param manageUser
	 * @return
	 */
	@RequestMapping("/saveorUpdate")
	@ResponseBody
	public ProcessResult saveorUpdate(HttpServletRequest request,
										@ModelAttribute ManageUser manageUser
//										@RequestBody ManageUser manageUser
										) {
		HttpSession session = request.getSession();
		ManageUser userLogin= (ManageUser) session.getAttribute(Session.manageUserLogin.name());
		
		ProcessResult pr= new ProcessResult();
		//更新     用户名、姓名、手机、邮箱、所属部门必填
		
		if(null==manageUser.getPhone()||"".equals(manageUser.getPhone())){
			pr.setStatus(false);
			pr.setMsg("用户名、真实姓名、角色不能为空！");
			return pr;
		}
		
		if(manageUser!=null &&"".equals(manageUser.getUserId())){
			//账号和手机号唯一
			List<ManageUser> user = manageUserDao.findUser(manageUser);
			if (user.size() != 0) {
				pr.setStatus(false);
				pr.setMsg("账号或手机号已存在");
				return pr;
			}
			manageUser.setUserId(IdCreater.getId());
			manageUser.setPassword(manageUserLoginService.generatePassword());
			manageUser.setCreateTime((DateTime.now().toDate()));
			manageUser.setCreater(userLogin.getUserName());//已登录的账号的username
			manageUser.setUpdater(userLogin.getUserName());
			manageUser.setStatus("1");//默认账号可用
			manageUser.setUpdateTime(DateTime.now().toDate());
			manageUserService.saveUser(manageUser);
			pr.setStatus(true);
			return pr;
		}else{
			
			ManageUser user = manageUserDao.findUserById(manageUser.getUserId());
			//修改手机的话  那需要判断是不是与其他人的重复
			if(!manageUser.getPhone().equals(user.getPhone())){
				List<ManageUser> existUsers = manageUserDao.findUserByPhone(manageUser.getPhone());
				if(existUsers!=null && existUsers.size()>0){
					pr.setStatus(false);
					pr.setMsg("手机号与其他人的重复");
					return pr;
				}else{
					user.setPhone(manageUser.getPhone());
				}
			}
			user.setDeptId(manageUser.getDeptId());
			user.setEmail(manageUser.getEmail());
			user.setRealName(manageUser.getRealName());
			user.setUpdater(userLogin.getUserName());
			user.setUpdateTime(DateTime.now().toDate());
			user.setGroupId(manageUser.getGroupId());
			manageUserDao.updateUser(user);
			if(user!=null && !user.getGroupId().equals(manageUser.getGroupId())){
				//更新关系表
				memberShipDao.saveMembership(manageUser);
			}
			pr.setStatus(true);
			return pr;
		}
	}
	
	/**
	 * 增加、编辑后台用户    =======暂时不提供部门信息（分中心）
	 * @param request
	 * @param manageUser
	 * @return
	 */
	@RequestMapping("/saveUser")
	@ResponseBody
	public Map<String, Object> saveUser(HttpServletRequest request,
										@ModelAttribute ManageUser manageUser
//										@RequestBody ManageUser manageUser
										) {
		Map<String, Object> result = Maps.newHashMap();
//		用户名、姓名、手机、邮箱、所属部门必填
		if(null==manageUser.getUserName()||"".equals(manageUser.getUserName())){
			result.put("success", false);
			result.put("msg","用户名、、真实姓名、角色不能为空！");
			return result;
		}
		
		HttpSession session = request.getSession();
		ManageUser userLogin= (ManageUser) session.getAttribute(Session.manageUserLogin.name());
		userLogin = new ManageUser();
		userLogin.setUserName("ld");
		//账号和手机号唯一
		List<ManageUser> user = manageUserDao.findUser(manageUser);
		if (user.size() != 0) {
			result.put("success", false);
			result.put("msg","账号或手机号已存在");
			return result;
		}
		manageUser.setUserId(IdCreater.getId());
		manageUser.setPassword(manageUserLoginService.generatePassword());
		manageUser.setCreateTime((DateTime.now().toDate()));
		manageUser.setCreater(userLogin.getUserName());//已登录的账号的username
		manageUser.setStatus("1");//默认账号可用
		manageUser.setUpdateTime(DateTime.now().toDate());
		
		manageUserService.saveUser(manageUser);
		result.put("success", true);
		return result;
	}
	
	
	/**
	 * 账号不能修改  手机号及其他信息可以修改
	 * @param request
	 * @param manageUser
	 * @return
	 */
	@RequestMapping("/updateUser")
	@ResponseBody
	public Map<String, Object> updateUser(HttpServletRequest request,
										@ModelAttribute ManageUser manageUser
//										@RequestBody ManageUser manageUser
										) {
		HttpSession session = request.getSession();
		ManageUser userLogin= (ManageUser) session.getAttribute(Session.manageUserLogin.name());
		userLogin = new ManageUser();
		userLogin.setUserName("ld");
		//================================================test  end
		
		
		
		Map<String, Object> result = Maps.newHashMap();
//		用户名、姓名、手机、邮箱、所属部门必填
		if(null==manageUser.getPhone()||"".equals(manageUser.getPhone())){
			result.put("success", false);
			result.put("msg","用户名、、真实姓名、角色不能为空！");
			return result;
		}
		ManageUser user = manageUserDao.findUserById(manageUser.getUserId());
		//修改手机的话  那需要判断是不是与其他人的重复
		if(!manageUser.getPhone().equals(user.getPhone())){
			List<ManageUser> existUsers = manageUserDao.findUserByPhone(manageUser.getPhone());
			if(existUsers!=null && existUsers.size()>0){
				result.put("success", false);
				result.put("msg","手机号与其他人的重复");
				return result;
			}else{
				user.setPhone(manageUser.getPhone());
			}
		}
		
		
		user.setDeptId(manageUser.getDeptId());
		user.setEmail(manageUser.getEmail());
		user.setRealName(manageUser.getRealName());
		user.setGroupId(manageUser.getGroupId());
		user.setUpdater(userLogin.getUserName());
		user.setUpdateTime(DateTime.now().toDate());
		manageUserDao.updateUser(user);
		return result;
	}
	/**
	 * 后台用户使用、禁用按钮
	 * @param request
	 * @param userId
	 * @param status
	 * @return
	 */
	@RequestMapping("/openUser")
	@ResponseBody
	public ProcessResult openUser(HttpServletRequest request,@RequestParam("userId")String userId,@RequestParam("status")String status) {
		ProcessResult pr= new ProcessResult();
		if(null!=userId){
			ManageUser user = manageUserDao.findUserById(userId);
			if(user!=null){
				manageUserDao.updateUserById(userId,status);
			}
		}
		pr.setStatus(true);
		return pr;
	}
	
	
	/**
	 * 重置密码
	 * @param request
	 * @param userId
	 * @return
	 */
	@RequestMapping("/resetPssword")
	@ResponseBody
	public ProcessResult resetPssword(HttpServletRequest request,@RequestParam("userId")String userId) {
		ProcessResult pr= new ProcessResult();
		ManageUser user = manageUserDao.findUserById(userId);
		user.setPassword(manageUserLoginService.generatePassword());
		pr.setStatus(true);
		return pr;
	}
	
	
	
	/**
	 * 删除用户
	 * @param manageUser
	 * @return
	 */
	@RequestMapping("del")
	@ResponseBody
	public ProcessResult userDel(@ModelAttribute ManageUser manageUser) {
		ProcessResult pr= new ProcessResult();
		if (Objects.isNull(manageUser.getUserId())) {
			pr.setStatus(false);
			pr.setMsg("删除有误，参数错误");
			return pr;
		}
		manageUserDao.delUser(manageUser);
		pr.setStatus(true);
		return pr;
	}
}
